<template>
  <div class="cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="cart-header">
          <h2>我的购物车</h2>
          <el-button type="danger" @click="clearCart" v-if="cartItems.length > 0">清空购物车</el-button>
        </div>
      </template>

      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车空空如也">
          <el-button type="primary" @click="goToProducts">去选购商品</el-button>
        </el-empty>
      </div>

      <div v-else>
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="product-info">
                <el-image :src="row.mainImage" class="product-image" fit="cover" />
                <div class="product-details">
                  <div class="product-name">{{ row.name }}</div>
                  <div class="product-price">¥{{ row.price }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              <div class="price">¥{{ row.price }}</div>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="180">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :min="1" :max="99" @change="updateQuantity(row)" size="small" />
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <div class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="removeItem(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-footer">
          <div class="cart-summary">
            <div class="summary-item">
              <span>商品总数：</span>
              <span>{{ totalQuantity }}件</span>
            </div>
            <div class="summary-item">
              <span>商品总价：</span>
              <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
          <div class="cart-actions">
            <el-button @click="goToProducts">继续购物</el-button>
            <el-button type="primary" @click="checkout">去结算</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 推荐商品 -->
    <div class="recommendations" v-if="recommendedProducts.length > 0">
      <h3 class="section-title">猜你喜欢</h3>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="12" :md="8" :lg="6" v-for="product in recommendedProducts" :key="product.id">
          <product-card :product="product" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductCard from '@/components/ProductCard.vue'
import request from '@/utils/request'

const router = useRouter()
const cartItems = ref([])

// 推荐商品
const recommendedProducts = ref([])

// 获取推荐商品
const fetchRecommendedProducts = async () => {
  try {
    // 获取所有商品
    const res = await request.get('/products', {
      params: {
        page: 1,
        size: 100, // 获取足够多的商品以便随机选择
        status: 1 // 只获取上架的商品
      }
    })

    if (res && res.code === 200 && res.data.content) {
      // 随机打乱商品数组
      const shuffledProducts = res.data.content.sort(() => Math.random() - 0.5)
      // 取前6个商品
      recommendedProducts.value = shuffledProducts.slice(0, 6).map(product => ({
        id: product.id,
        name: product.name,
        price: product.price,
        originalPrice: product.originalPrice,
        mainImage: product.mainImage || 'https://element-plus.org/images/element-plus-logo.svg',
        sales: product.sales,
        isHot: product.isHot === 1,
        isNew: product.isNew === 1
      }))
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error)
    ElMessage.error('获取推荐商品失败')
  }
}

// 计算商品总数
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算商品总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
})

// 加载购物车数据
const loadCartItems = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      // 如果未登录，从localStorage获取购物车数据
      const items = JSON.parse(localStorage.getItem('cartItems') || '[]')
      cartItems.value = items
      return
    }

    // 如果已登录，从后端API获取购物车数据
    const res = await request.get(`/cart/user/${userInfo.id}`)
    if (res && res.code === 200 && res.data) {
      // 转换后端数据格式为前端期望的格式
      cartItems.value = res.data.map(item => ({
        id: item.productId, // 前端使用productId作为商品ID
        cartId: item.id, // 保存购物车项ID用于更新和删除
        name: item.productName,
        price: item.price,
        mainImage: item.productImage,
        quantity: item.quantity
      }))
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    // 如果API调用失败，回退到localStorage
    const items = JSON.parse(localStorage.getItem('cartItems') || '[]')
    cartItems.value = items
  }
}

// 更新购物车数据
const saveCartItems = () => {
  localStorage.setItem('cartItems', JSON.stringify(cartItems.value))
  // 触发购物车更新事件
  window.emitter?.emit('cart-updated')
}

// 更新商品数量
const updateQuantity = async (item) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      saveCartItems()
      return
    }

    // 如果已登录，调用后端API更新
    if (item.cartId) {
      await request.put(`/cart/${item.cartId}`, null, {
        params: { quantity: item.quantity }
      })
      ElMessage.success('数量已更新')
    }
  } catch (error) {
    console.error('更新购物车数量失败:', error)
    ElMessage.error('更新数量失败')
    // 重新加载购物车数据
    loadCartItems()
  }
}

// 删除商品
const removeItem = async (item) => {
  try {
    await ElMessageBox.confirm('确定要从购物车中删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      cartItems.value = cartItems.value.filter(i => i.id !== item.id)
      saveCartItems()
      ElMessage.success('商品已从购物车中删除')
      return
    }

    // 如果已登录，调用后端API删除
    if (item.cartId) {
      await request.delete(`/cart/${item.cartId}`)
      // 重新加载购物车数据
      await loadCartItems()
      ElMessage.success('商品已从购物车中删除')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除购物车商品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 清空购物车
const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      cartItems.value = []
      saveCartItems()
      ElMessage.success('购物车已清空')
      return
    }

    // 如果已登录，调用后端API清空
    await request.delete(`/cart/user/${userInfo.id}`)
    cartItems.value = []
    ElMessage.success('购物车已清空')
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('清空购物车失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 去商品页面
const goToProducts = () => {
  router.push('/home/products')
}

// 去结算
const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算')
    return
  }

  // 检查用户是否登录
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (!userInfo.id) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  // 跳转到结算页面
  router.push('/home/checkout')
}

onMounted(() => {
  loadCartItems()
  fetchRecommendedProducts() // 获取推荐商品
})
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.cart-card {
  margin-bottom: 30px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.empty-cart {
  padding: 30px 0;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 14px;
  margin-bottom: 8px;
}

.product-price {
  color: #F56C6C;
  font-size: 14px;
}

.price,
.subtotal {
  font-size: 14px;
  color: #606266;
}

.subtotal {
  color: #F56C6C;
  font-weight: 500;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.cart-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #F56C6C;
}

.cart-actions {
  display: flex;
  gap: 10px;
}

.recommendations {
  margin-top: 30px;
}

.section-title {
  font-size: 18px;
  margin-bottom: 20px;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}
</style>